/*
Skyler Sell
CSCD 330 Spring 2007
HW 1

Client program that connects to a server on port 2007 and 
takes strings from stdin, sends the string to the server, then
gets a string from the server.  If the server sends the string "closing"
the client closes out.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 80

int main(int argc, char *argv[])
{
	int sockfd, nread;

	struct sockaddr_in serv_addr;
	FILE *fp;
	char buf[BUFSIZ];
	char *htmlPtr, *bufPtr = buf;
	/* char inBuf[100]; */
	int i;

	if(argc != 2)
	{
		fprintf(stderr, "usage: %s IPaddr\n", argv[0]);
		exit(1);
	}
	
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		fputs("socket returned null\n", stderr);
		exit(2);
	}

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
	serv_addr.sin_port = htons(PORT);
	
	if(connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
	{
		fputs("connection error\n", stderr);
		exit(3);
	}

	write(sockfd, "GET / HTTP/1.0\n\n", sizeof("GET / HTTP/1.0\n\n"));
	fp = fopen("out.html", "w");

	i = 0;
	while ((nread = read(sockfd, buf, sizeof(buf))))
	{
		if (i == 0)
		{
			htmlPtr = strstr(bufPtr, "<html>");
			if (htmlPtr != NULL)
			{
				puts("writing page to out.html");
				fprintf(fp, "%s", htmlPtr);	
				i++;
			}
		}
		else
		{
			if (nread <= 0)	break;
			buf[nread] = 0;
			fprintf(fp, "%s", buf);
		}
	}
	fputc('\n', fp);
	fclose(fp);
	close(sockfd);

	return 0;
}

